package gov.kqqzyyy.monkey.ydhl.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import adapter.PlanCheckAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.ydhl.R;
import mytools.DateUtil;
import mytools.MyBaseActivity;
import mytools.MyServiceUtil;
import objects.OrderDetail;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//计划执行
public class PlanCheckActivity extends MyBaseActivity implements SwipeRefreshLayout.OnRefreshListener, Switch.OnCheckedChangeListener, RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.oc_tb_switch)
    Switch mSwitch;
    @BindView(R.id.oc_swipe)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.filter_radiogroup)
    RadioGroup radioGroup;
    @BindView(R.id.oc_expand)
    ExpandableListView expandableListView;
    @BindView(R.id.oc_tb_brxm)
    TextView brxmText;

    private Call<String> yzjhCall;
    private Call<String> checkYZJHCall;

    private PlanCheckAdapter mPlanCheckAdapter;
    private List<OrderDetail> mYZJHList;
    private List<OrderDetail> parentList;

    private String mStartDate, mEndDate;

    private MyHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plan_check);
        ButterKnife.bind(this);

        setSwipeRefreshLayout(swipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.holo_green_dark, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(this);

        mSwitch.setOnCheckedChangeListener(this);

        mPlanCheckAdapter = new PlanCheckAdapter(this);
        expandableListView.setAdapter(mPlanCheckAdapter);

        radioGroup.setOnCheckedChangeListener(this);

        handler = new MyHandler(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        mToolbar.setTitle("计划复核");   //设置标题
        mToolbar.setTitleTextColor(Color.WHITE);

        brxmText.setText("");
        brxmText.setTextColor(Color.WHITE);
        setSupportActionBar(mToolbar);

        String dateString = DateUtil.getDateFormat(new Date());
        mStartDate = dateString;
        mEndDate = dateString;

        doGetYZJH(true, "", mStartDate, mEndDate);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (yzjhCall != null && yzjhCall.isExecuted()) {
            yzjhCall.cancel();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_plan_check, menu); //解析menu布局文件到menu
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_selectall:
                boolean isSelectAll = !mPlanCheckAdapter.isSeleceAll();
                mPlanCheckAdapter.selectAll(isSelectAll);
                break;
            case R.id.item_check:
                break;
        }
        return super.onOptionsItemSelected(item);
    }



    @Override
    public void onRefresh() {
        doGetYZJH(false, "", mStartDate, mEndDate);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            mSwitch.setText(" 已复核 ");
        } else {
            mSwitch.setText(" 未复核 ");
        }
        doGetFilterCondition();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        doGetFilterCondition();
    }


    //核对、执行医嘱
    private void doCheckYZJH(String ygdm, String tmbh) {
        checkYZJHCall = MyServiceUtil.doCheckYZJH(ygdm, tmbh);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        };
        checkYZJHCall.enqueue(callback);
    }

    private void doGetFilterCondition() {
        int hdbz = mSwitch.isChecked() ? 1 : 0;
        int lxxh = -1;
        switch (radioGroup.getCheckedRadioButtonId()) {
            case R.id.filter_all:
                lxxh = -1;
                break;
            case R.id.filter_sy:
                lxxh = 1;
                break;
            case R.id.filter_zs:
                lxxh = 2;
                break;
            case R.id.filter_kf:
                lxxh = 3;
                break;
            case R.id.filter_other:
                lxxh = 4;
                break;
        }
        doSetFilterData(hdbz, lxxh);
    }

    private void doSetFilterData(int hdbz, int lxxh) {
        parentList = new ArrayList<>();
        ArrayMap<OrderDetail, List<OrderDetail>> mDataSet = new ArrayMap<>();
        for (OrderDetail ocYZJH : mYZJHList) {
            boolean condition = false;
            if (ocYZJH.getHDBZ() == null) {

                if (hdbz == 0) {
                    condition = true;
                } else if (Integer.valueOf(ocYZJH.getHDBZ()) == hdbz) {
                    condition = true;
                }

                if (lxxh != -1) {
                    condition = condition && (ocYZJH.getLXXH() == lxxh);
                }

                if (condition) {
                    if (ocYZJH.getYZZX().equals("1")) {
                        parentList.add(ocYZJH);
                        mDataSet.put(ocYZJH, null);
                    } else {
                        for (OrderDetail parentYZJH : parentList
                                ) {
                            if (ocYZJH.getTMBH().equals(parentYZJH.getTMBH())) {
                                List<OrderDetail> childList = mDataSet.get(parentYZJH);
                                if (childList == null) {
                                    childList = new ArrayList<>();
                                }
                                childList.add(ocYZJH);
                                mDataSet.put(parentYZJH, childList);
                            }
                        }
                    }
                }
            }
        }
        mPlanCheckAdapter.setDataSets(mDataSet);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 1300:
            case 1301:
                getmBCRManager().open(getApplicationContext());
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private static class MyHandler extends Handler {

        WeakReference<PlanCheckActivity> mActivity;

        MyHandler(PlanCheckActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            PlanCheckActivity activity = mActivity.get();
            switch (msg.what) {
                case 0x11:
                    activity.getmBCRManager().stopScan();

//                    activity.new MyPatientBRBSTask().execute(activity.mBCRTicketInfo[0].getTicketValue());
                    break;
                case 0x99:
//                    activity.mBCRManager.stopScan();
                    activity.getmBCRManager().stopScan();
                    Toast.makeText(activity, "扫描数据错误！", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    }
}
